<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/4
 * Time: 19:30
 */

namespace app\admin\model;


use think\Config;
use think\Model;
use app\admin\logic\Auth;
use tree\Tree;
use think\Cache;

class AuthRule extends Model
{
//    protected $not_check_id = [1];//不检测权限的管理员id
//    protected $not_check_url = ['admin/index/index', 'admin/sys/clear', 'admin/index/lang', 'common/ajax/region', 'admin/ajax/region', 'admin/ajax/qudao'];//不检测权限的url
    protected $autoWriteTimestamp = 'int';
    private static $instance = null;

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 状态获取器
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [1 => '<span class="label label-success">显示</span>', 0 => '<span class="label label-danger">隐藏'];
        return $status[$data['status']];
    }

    /**
     * 是否检测获取器
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getNotcheckTextAttr($value, $data)
    {
        $status = [1 => '<span class="label label-danger">No测</span>', 0 => '<span class="label label-success">检测'];
        return $status[$data['notcheck']];
    }

    /**
     * 获取指定url的id(可能为显示状态或非显示状态)
     * @param string $url 为空获取当前操作的id
     * @param int $status 1表示取显示状态,为空或为0则不限制
     * @return int -1表示不需要检测 0表示无后台菜单 其他表示当前url对应id
     */
    public function get_url_id($url = '', $status = 0)
    {
        $url = $url ?: request()->module() . '/' . request()->controller() . '/' . request()->action();
        $url = strtolower($url);
        if (in_array($url,Config::get('admin.auth')['not_check_id'])) return -1;
        $where['name'] = $url;
        if ($status) $where['status'] = $status;
        $menu_id = self::where($where)->order('level desc,sort')->field('id,notcheck')->find();//查找当前节点的id
        $menu_id = $menu_id['notcheck'] == 1 ? -1 : $menu_id['id'];
        return $menu_id;
    }

    /**
     * 权限检测
     * @param int $id
     * @return bool
     */
    public function check_auth($id = 0)
    {
        if (is_string($id) && !empty($id)) {
            $id = $this->get_url_id($id);
        } else {
            $id = $id ?: $this->get_url_id();
        }
        if ($id == -1) return true;
        $uid = session('admin_user.adminid');
        if (in_array($uid, Config::get('admin.auth')['not_check_id'])) return true;
        $auth_ids_list = Cache::tag('menu')->get('auth_ids_list_' . $uid);
        if (empty($auth_ids_list)) {
            $auth = Auth::instance();
            $auth_ids_list = $auth->getAuthList($uid, 1, 'id');
            Cache::tag('menu')->set('auth_ids_list_' . $uid, $auth_ids_list);
        }
        if (empty($auth_ids_list)) return false;
        if (in_array($id, $auth_ids_list)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 手机端权限检测
     * @return array
     */
    public function mobilecheck()
    {
        $auth_ids_list = Cache::tag('menu')->get('auth_ids_list_' . UID);
        if (empty($auth_ids_list)) {
            $auth = Auth::instance();
            $auth_ids_list = $auth->getAuthList(UID, 1, 'id');
            Cache::tag('menu')->set('auth_ids_list_' . UID, $auth_ids_list);
        }
        return $auth_ids_list;
    }

    /**
     * 获取权限菜单
     * @return array
     */
    public function get_admin_menus()
    {
        $uid = session('admin_user.adminid');
        $menus = Cache::tag('menu')->get('menus_admin_' . $uid);
        if ($menus) return $menus;
        $where['status'] = 1;
        if (!in_array($uid, Config::get('admin.auth')['not_check_id'])) {//判断不检测的管理员 或者是超管
            $auth_ids_list = Cache::tag('menu')->get('auth_ids_list_' . $uid);
            if (empty($auth_ids_list)) {//判断缓存是否存在当前用户的权限缓存 不存在就去数据库重新获取
                $auth = Auth::instance();
                $auth_ids_list = $auth->getAuthList($uid, 1, 'id');
                //获取到权限缓存后存入缓存中
                Cache::tag('menu')->set('auth_ids_list_' . $uid, $auth_ids_list);
            }
            if (empty($auth_ids_list)) return [];//没权限然后返回空
            $where['id'] = array('in', $auth_ids_list);
        }
        $data = self::where($where)->order('sort')->select();
        $data = collection($data)->toArray();
        $tree = new Tree();
        $tree->init($data, ['child' => '_child', 'parentid' => 'pid']);
        $menus = $tree->get_arraylist($data);
        Cache::tag('menu')->set('menus_admin_' . $uid, $menus);
        return $menus;
    }

    /**
     * 获取权限菜单
     * @return array
     */
    public static function get_ruels_tree()
    {
        $data = self::order('sort')->where(['notcheck' => 0])->select();
        $data = collection($data)->toArray();
        $tree = new Tree();
        $tree->init($data, ['child' => 'sub', 'parentid' => 'pid']);
        $rst = $tree->get_arraylist($data);
        return $rst;
    }

    /**获得所有的类别类别（从缓存中）
     * @return false|mixed|\PDOStatement|string|\think\Collection   返回数组
     */
    public function getAllAuths()
    {
        $allAuths = Cache::get('allAuths');
        if (!empty($allAuths)) return $allAuths;
        $allAuths = $this->order('sort')->select();
        if (empty($allAuths)) return $allAuths;
        $allAuths = collection($allAuths)->append(['status_text'])->toArray();
        Cache::set('allAuths', $allAuths);
        return $allAuths;
    }

}